import React, { Component } from "react"
import ReactDOM from 'react-dom'
import { Input, Icon } from 'antd'
import 'styles/pay/edit-cell.scss'

class EditInput extends Component {

  state = {
    editing: false,
    value: this.props.value
  };

  componentWillReceiveProps = nextProps => {
    if (nextProps.value !== this.state.value) {
      this.setState({ value: nextProps.value });
    }
  };

  toggleEdit = () => {
    const { disable } = this.props;
    if (!disable) {
      this.setState({ editing: true }, () => {
        setTimeout(() => {
          const { value } = this.state;
          this.inputRef.focus();
          let length = (value + '').length;
          ReactDOM.findDOMNode(this.inputRef).setSelectionRange(length, length);
        }, 0)
      });
    }
  };

  changeBlur = e => {
    this.onChange();
    let temp = { editing: false };
    e && (temp.value = e.target.value);
    this.setState(temp);
  };

  changeValue = e => {
    this.setState({ value: e.target.value },() => {
      setTimeout(() => {
        let length = this.state.value.length;
        this.inputRef && ReactDOM.findDOMNode(this.inputRef).setSelectionRange(length, length);
      }, 0);
    });
  };

  onChange = () => {
    const { value } = this.state;
    const { onChange } = this.props;
    onChange(value);
  };

  keyDown = e => {
    if (e.keyCode === 13) {
      this.changeBlur()
    }
  };

  render() {
    const { editing, value } = this.state;
    const { style, render } = this.props;
    let children = editing ? (
      <Input
        onBlur={this.changeBlur}
        value={value}
        onChange={this.changeValue}
        style={{ width: '100%' }}
        ref={inputRef => this.inputRef = inputRef}
        onKeyDown={this.keyDown}
      />
    ) : (
      <div className='simulate-form' onClick={this.toggleEdit} style={style}>
        <span className='edit-cell-show'>{render ? render(value) : value}</span>
        <Icon type="edit" className="editable-cell-icon" />
      </div>
    );
    return (
      <div>{children}</div>
    )
  }

}

export default EditInput
